-- tests scene
local layer = nil
local scene = nil
local newSceneUI = nil

local Btn_Tips  = 0x01
local Btn_Item1 = 0x02
local Btn_Item2 = 0x03
local Btn_Item3 = 0x04

require "lua/ui_fight"

-- 道具赠送
GifsItemsForMonster = 20
GifsItemsForScore = 200000


RoleBegPosY = gdv(DWinSizeHeight * 0.84)
MonsterBegPosX = gdv(DWinSizeWidth * 1.09)
PlayerBegPosX = gdv(DWinSizeWidth * 0.22)
MonsterMoveToPy = 1 --移动到玩家面前的次数
MonsterMoveFps  = 1 --默认移动频率
MonsterMoveSpeed    = 5 --移动速度
MonsterRefFps = 5 * 60 --怪物刷新间隔
AttackRange = gdv(130) --攻击范围(近战
AttackRangeRemote = 800 --攻击范围(远程
MonsterToPosX = PlayerBegPosX + gdv(80) --玩家面前

--换宝石延长时间
BrickDelayTime = 2.0

ChangeBrickTimer = 5 * 60--5秒变换一次晶魂

GemSumsScore = {
    [3]=300,
    [4]=500,
    [5]=1000,
    [6]=1200,
    [7]=1400,
    [8]=1600,
    [9]=3200,
    [10]=3800,
    [11]=4000,
    [12]=4200,
}

ComboSkill = 6 --连消技能数
MonsterMax  = 4 --最大怪物数


local _lastTips = 0
local _TipsTimes = 5 --提示间隔(秒,久未找到砖块时提示

local function initWithLayer(stage)
    local _stage = stage
    local _on_result = false
    local _skill_monster_sums = 0
    
    local _gameComplete = nil
    local _menuCallbackItem = nil
    
    
    local tabletipsSp = {}
    _lastTips = 0
    local _tipslayer = CCLayer:create()
    scene:addChild(_tipslayer, 4)
    
    --血屏文本
    local _txtMyhpCut = nil --文本
    local _txtMyhpCutBg = nil --数字背景
    
    local _btnItemBaozou = nil
    local _btnItemWudi = nil
    local _btnItem_AutoSl = nil
    local _btnItem_Tips = nil
    
    
    -----------------------------------------游戏逻辑
    local _PlayerTable = {} --角色列表
    local _PlayerHTable = {} --角色头像列表
    local _Player = nil --当前玩家角色
    
    -- 战场layer
    local _layerBattle = BattleField:new()
    -- 总分数
    local _gameScore = 0
    local _gameSoulPer = 0
    local _gameCrystal = GetCrystal() -- 当前水晶币
    local _comboSums = 0-- 累加消除数
    
    ---- 每隔5秒变换一次魂晶颜色
    local _changetime = 0
    
    --当砖块阵重组时,停止怪物行为更新
    local _ResBrickTime = 0
    
    -- 临时道具
    local tempItemsTable = {
        [Item_HpItem]=0,
        [Item_Wudi]=0,
        [Item_Fuhuo]=0,
        [Item_AutoSl] = 0,
        [Item_Tips] = 0,
    }
    
    ----------读取关卡信息
    local _StageInfos = Stage_Infos_ZJWG[stage]
    -- 初始宝石
    local gemType = _StageInfos[PGemType]
    
    -- 无限暴走
    local _OnBaoForever = false
    local _OnBaozouTime = 0
    -- 无敌状态
    local _OnWudi = false
    local _OnWudiLTime = 0
    
    local _func_changePlayer = nil
    local _func_onShowResult = nil
    -- 暴走模式开启时机
    local _baozoutime = 0
    local _onbaozou = false
    ---- 重新判定宝石排列
    
    -- 每次结束后都会判定得到可交换列表
    local _swaplist = {}
    local function TestSwap(gem1, gem2)
        if gem1 ~= nil and gem2 ~= nil then
            has,rvalue = has_Puz_Gems(_GGemTable, gem1, gem2)
            return has
        end
        return false
    end
    
    -- 获取可排列的宝石列表
    local function getSwapList()
        _swaplist = {}
        -- 每次尝试与右边/下边的宝石交换,看是否能交换成功
         for r=0,Gems_Rows-1 do
            for c=0,Gems_Cols-1 do
                local cgem = _GGemTable[getIndex(r,c)]
                if cgem ~= nil then
                    --右边
                    local has, delobj = has_Puz_GemCon(_GGemTable, cgem)
                    --print(has,delobj)
                    if has and #delobj.delgems > Puz_Number then
                        --- 可以交换
                        table.insert(_swaplist, delobj)
                    end
                end
            end
        end
        --print("getSwapList",#_swaplist)
    end
    
    local _timerIDNew = nil
    local function onNewRoundLeat()
        if _timerIDNew ~= nil then
            CCDirector:sharedDirector():getScheduler():unscheduleScriptEntry(_timerIDNew)
            _timerIDNew = nil
        end
        getSwapList()
        if #_swaplist <= 0 then
            --如果没有可排列的则重新生成
            _func_deleteAllGems()
            --延迟游戏
            _ResBrickTime = BrickDelayTime
            return false
        end
        return true
    end
    
    
    
    
    -- 点击提示按钮
    local _tipsGems = nil
    local _onShowTips = false
    
    local function clearGemsTips()
        _lastTips = 0
        _onShowTips = false
        
        table.foreach(tabletipsSp, function(k,tipsp)
            _tipslayer:removeChild(tipsp, true)
        end)
        tabletipsSp = {}
    end
    
    local function BtnTipsCallback()
        clearGemsTips()
        
        if #_swaplist > 0 then
            --随机一个
            local idx = math.random(1,#_swaplist)
            local tipsItem = _swaplist[idx]
            
            table.foreach(tipsItem.delgems, function(k, idx)
                cgem = _GGemTable[idx]
                if cgem~=nil then
                    --local array = CCArray:create()
                    --array:addObject(CCTintTo:create(0.5, 255, 100, 100))
                    --array:addObject(CCTintTo:create(0.5, 255, 255, 100))
                    --array:addObject(CCTintTo:create(0.5, 100, 255,200))
                    --array:addObject(CCTintTo:create(0.5, 100, 255, 255))
                    --array:addObject(CCTintTo:create(0.5, 100, 100, 255))
                    --array:addObject(CCTintTo:create(0.5, 255, 100, 255))
                    --cgem.img:runAction(CCRepeatForever:create(CCSequence:create(array)))
                    
                    
                    local px,py = cgem:GetPosition()
                    local tipSp = CCSprite:createWithSpriteFrameName("TEBrick_Pick_02.png")
                    tipSp:setPosition(ccp(px,py))
                    _tipslayer:addChild(tipSp)
                    table.insert(tabletipsSp, tipSp)
                    
                    local arr1 = CCArray:create()
                    arr1:addObject(CCFadeTo:create(0.5, 100))
                    arr1:addObject(CCFadeTo:create(0.5, 255))
                    tipSp:runAction(CCRepeatForever:create(CCSequence:create(arr1)))
                end
            end)
            
            _onShowTips = true
        end
    end
    
    -- 按钮回调函数
    local function menuCallback(tag)
        if tag == Btn_Tips then
            --BtnTipsCallback()
        elseif tag == Btn_Item1 then
        elseif tag == Btn_Item2 then
        end
        
        Play_Effect(sme_Click)
    end
    
    local function updateItemsCount()
        --_btnItemBaozou:updateCut(GetItems(Item_Baozou))
        -- ((加上临时道具
        -- 如果拥有道具数量,则显示成其它样式
        if tempItemsTable[Item_HpItem] > 0 then
            local frame = CCSpriteFrameCache:sharedSpriteFrameCache():spriteFrameByName("levelBg2.png")
            _txtMyhpCutBg:setDisplayFrame(frame)
        else
            local frame = CCSpriteFrameCache:sharedSpriteFrameCache():spriteFrameByName("levelBg.png")
            _txtMyhpCutBg:setDisplayFrame(frame)
        end
        
        _txtMyhpCut:setString(GetItems(Item_HpItem) + tempItemsTable[Item_HpItem])

        -- 如果拥有道具数量,则显示成其它样式
        if tempItemsTable[Item_Wudi] > 0 then
            local frame = CCSpriteFrameCache:sharedSpriteFrameCache():spriteFrameByName("levelBg2.png")
            _btnItemWudi.priceBg:setDisplayFrame(frame)
        else
            local frame = CCSpriteFrameCache:sharedSpriteFrameCache():spriteFrameByName("levelBg.png")
            _btnItemWudi.priceBg:setDisplayFrame(frame)
        end
        
        _btnItemWudi:updateCut(GetItems(Item_Wudi) + tempItemsTable[Item_Wudi])
        
        
        _btnItem_AutoSl:updateCut(GetItems(Item_AutoSl))
        _btnItem_Tips:updateCut(GetItems(Item_Tips))
    end
    
    _func_wudi = function(b)
        if b then
            _OnWudi = true
            _OnWudiLTime = _OnWudiLTime + GItemP_Wudi
            
            GFunc_ShowWudiEffs()
            
            _Player.isWudi = true
        else
            _OnWudi = false
            GFunc_HideWudiEffs()
            
            _Player.isWudi = false
        end
    end
    
    _func_baozou = function(b)
        if b then
            _OnBaoForever = true
            GFunc_ShowBaozouEffs()
            
            ---伤害加深100%
            _Player.isBaozou = true
            
            _OnBaozouTime = os.clock()
        else
            _Player.isBaozou = false
            
            _OnBaoForever = false
            if not _onbaozou then
                Gfunc_DelBazouEffs()
            end
        end
    end
    
    _menuCallbackItem = function(tag)
        -- 有临时道具的情况下,优先使用临时道具
        local hastemp = false
        local usetemp = false
        if tempItemsTable[tag] > 0 then
            hastemp = true
        end
        
        local function useTempItems()
            if hastemp then
                tempItemsTable[tag] = tempItemsTable[tag] - 1
            end
        end
        
        if tag == Item_HpItem then
            --生命值不满的情况下使用
            if _Player._hp ~= _Player._hpmax and (hastemp or UseItems(Item_HpItem)) then
                useTempItems()
                
                -- 增加100生命
                if _Player._hp < 0 then
                    _Player._hp = 0
                end
                _Player._hp = _Player._hp + 100 --_Player._hpmax
                if _Player._hp > _Player._hpmax then
                    _Player._hp = _Player._hpmax
                end
                
                -- 回血效果
                local _lblSoul = GameNumbers:new(vNumberHurt)
                _lblSoul:addLayer(CCDirector:sharedDirector():getRunningScene())
                _lblSoul:setNumber(100)
                _lblSoul:setPosition(ccp(PlayerBegPosX, RoleBegPosY))
                _lblSoul:runAction_MoveBy(1.0, ccp(0,100), true)
            else
                Play_Effect(sme_ClickError)
            end
            
            --_func_onShowResult(true)
        elseif tag == Item_Wudi then
            if not _OnWudi then
                if (hastemp or UseItems(Item_Wudi)) then
                    useTempItems()
                    
                    _func_wudi(true)
                end
            else
                Play_Effect(sme_ClickError)
            end
            
            --_Player:onAttack(true)
            --_func_onShowResult(false)
        elseif tag == Item_Baozou then
            if not _OnBaoForever then
                if UseItems(Item_Baozou) then
                    _func_baozou(true)
                end
            else
                Play_Effect(sme_ClickError)
            end
        elseif tag == Item_AutoSl then
            local irow = Gems_Rows-1
            local icol = 0
            local cgemss = _GGemTable[getIndex(irow,icol)]
            if cgemss and UseItems(Item_AutoSl) then
                _func_UseToBom(cgemss, Item_Bom)
            end
        elseif tag == Item_Tips then
            --当前还必须没有其它提示
            if not _onShowTips and UseItems(Item_Tips) then
                BtnTipsCallback()
            end
            
            --_func_onShowResult(true, true)
        end
        
        updateItemsCount()
    end
    -------- ui
    
    ---- 显示游戏结果
    _func_onShowResult = function (bwin, bend)
        if _on_result then
            return
        end
        Stop_AllEffect()
        
        _on_result = true
        --GamePasueHelper()
        _GameEndRun = true
        
        -- 继续/下一关
        local function onNextStage()
            Create_TJMS_SceneRun(_stage + 1)
            Play_Effect(sme_Click)
        end
        
        -- 重新开始
        local function onRestStage()
            Create_TJMS_SceneRun(_stage)
            Play_Effect(sme_Click)
        end
        
        local function onRestStageWXHL()
            Create_WXHL_SceneRun()
            Play_Effect(sme_Click)
        end
        
        local _resFunc = onRestStage
        if _stage == #Stage_Infos_ZJWG then
            _resFunc = onRestStageWXHL
        end
        
        -- 复活
        local function onRestHp(buseItems)
            if buseItems or UseItems(Item_Fuhuo) then
                _on_result = false
                _GameEndRun = false
                -- 所有角色满血
                table.foreach(_PlayerTable, function(k,py)
                    py._hp = py._hpmax
                    --头像
                    _PlayerHTable[py.id]:setColor(ccc3(255,255,255))
                end)
                scene:removeChildByTag(10086, true)
                GameResumeHelper()
            end
        end
        
        -----------------  如果拥有赠送的复活道具,则直接复活
        if tempItemsTable[Item_Fuhuo] > 0 then
            --如果有临时复活道具,则直接进行复活
            if tempItemsTable[Item_Fuhuo] > 0 then
                tempItemsTable[Item_Fuhuo] = tempItemsTable[Item_Fuhuo] - 1
                updateItemsCount()
                
                --显示一个复活道具与文字描述
                local tempFHlayer = CCLayer:create()--CCLayerColor:create(ccc4(0,0,0,100))
                local sw, sh = 300, 250
                tempFHlayer:setContentSize(CCSizeMake(sw, sh))
                tempFHlayer:setPosition(gdccp(DWinSizeWidth/2 - sw/2, DWinSizeHeight/2 - sh/2))
                
                local _bgSprBg = CCSprite:createWithSpriteFrameName("UIdaoju024.png")
                _bgSprBg:setPosition(gdccp(sw/2, sh/2+25))
                tempFHlayer:addChild(_bgSprBg,1)
                
                local _bgSpr = CCSprite:createWithSpriteFrameName("fh_ico.png")
                _bgSpr:setPosition(gdccp(sw/2, sh/2+50))
                tempFHlayer:addChild(_bgSpr,1)
                
                local lblFHSums = CCLabelTTF:create("自动使用了赠送的复活道具", "Arial", FontSize)
                lblFHSums:setPosition(gdccp(sw/2, sh/2))
                tempFHlayer:addChild(lblFHSums,1)
                
                for i,vb in pairs({_bgSprBg, _bgSpr, lblFHSums}) do
                    local array = CCArray:create()
                    array:addObject(CCFadeIn:create(1))
                    array:addObject(CCFadeTo:create(1.5, 255))
                    array:addObject(CCFadeOut:create(0.5))
                    local seq = CCSequence:create(array)
                    vb:runAction(CCSequence:createWithTwoActions(seq, CCCallFuncN:create(function()
                        if tempFHlayer ~= nil then
                            CCDirector:sharedDirector():getRunningScene():removeChild(tempFHlayer, true)
                            tempFHlayer = nil
                        end
                    end)))
                end
                
                CCDirector:sharedDirector():getRunningScene():addChild(tempFHlayer)
                
                onRestHp(true)
                return
            end
        end
        
    
        ------- 显示结果
        local layerRestul = CCLayerColor:create(ccc4(0,0,0,80))
        local ResultMainMenu = CCMenu:create()
        -- 主菜单大小
        ResultMainMenu:setContentSize(CCSizeMake(DWinSizeWidth,  DWinSizeHeight))
        -- 设置坐标
        ResultMainMenu:setPosition(0, 0)
        -- 添加至主菜单层
        layerRestul:addChild(ResultMainMenu, 5)
        scene:addChild(layerRestul, 5, 10086)
        
        --- 遮罩
        local btnItem = nil
        btnItem = CCMenuItemLabel:create(CCLabelTTF:create("", "Arial",FontSize))
        btnItem:setPosition(gdccp(DWinSizeWidth/2, DWinSizeHeight/2))
        btnItem:setContentSize(CCSizeMake(DWinSizeWidth,  DWinSizeHeight))
        ResultMainMenu:addChild(btnItem,100)
        
        local _widthb = 94
        local _heightb = 32
        local btnSpriteN = nil
        local btnSpriteS = nil
        local btnItem = nil
        
        -- 最后一关之前
        local invW = 200
        local invSums = 2
        local bpx = DWinSizeWidth/2 + (1-invSums)*invW/2
        local bpy = DWinSizeHeight/2 - 80
        local index = 0
        
        local restbg = nil
        local restlg = nil
        
        if bwin then
            -- 如果是第一次过关,会得到水晶币奖励
            if GetZJWGDatas(_stage) <= 0 then
                UpdateZJWGatas(_stage, 1)
                AddCrystal(_StageInfos[PScore])
            end
            
            Play_BackgroundMusic(sm_Win)
            -- 最后一关之前
            invW = 200
            bpx = DWinSizeWidth/2 + (1-invSums)*invW/2
            index = 0
            
            --最后一关前显示下一关
            if _stage < #Stage_Infos_ZJWG - 1 then
                -------还需要达成关卡解锁条件
                --local nextStage = _stage + 1
                ---- 获得关卡积分与过关积分,查看是否过关
                --local indxStage = nextStage + 1
                --local hlwsIdx = math.ceil(indxStage/4) * 4 - 1
                --local score = GetStageDatas(hlwsIdx)
                --local _StageInfos = StageInfos_HLWS[hlwsIdx]
                
                local isenable = true
                --第一关以魂力无双的积分为准,
                --if nextStage%4 ~= 0 then
                --    --前一关积分
                --    score = GetZJWGDatas(nextStage-1)
                --    -- 是否通过
                --    if score > 0 then
                --        -- 禁用按钮
                --        isenable = true
                --    end
                --else
                --    if _StageInfos == nil or score >= _StageInfos[PScore] then
                --        -- 禁用按钮
                --        isenable = true
                --    end
                --end
                if isenable then
                    invSums = 3
                    bpx = DWinSizeWidth/2 + (1-invSums)*invW/2
                    
                    local btnItem = GFunc_CreateButtonP("rst_next.png", onNextStage)
                    btnItem:setPosition(gdccp(bpx + invW * index, bpy))
                    ResultMainMenu:addChild(btnItem)
                    index = index + 1
                end
            else
                --通关成就
                --如果是最后一关,成就通过
                Func_DataStatis(DS_ModeEnd, GameMode_ZJWG)
                
                --解锁无限回廊
                local achName = table.concat({DS_ModeOp , "_", GameMode_WXHL})
                local value = 1
                local achValue = GetAchieves(achName)
                if achValue < value then
                    Func_DataStatis(DS_ModeOp, GameMode_WXHL)
                end
            end
            
            local btnItem = GFunc_CreateButtonP("rst_rest.png", _resFunc)
            btnItem:setPosition(gdccp(bpx + invW * index, bpy))
            ResultMainMenu:addChild(btnItem)
            index = index + 1
            
            
            local btnItem = GFunc_CreateButtonP("fh_return.png", MainMenuCallback)
            btnItem:setPosition(gdccp(bpx + invW * index, bpy))
            ResultMainMenu:addChild(btnItem)
            
            restbg = s_Game_WinImgBG
            restlg = s_Game_WinImg
        else
            restbg = s_Game_LostImgBG
            restlg = s_Game_LostImg
            if bend then
                Play_BackgroundMusic(sm_Lost)
                -- 最后一关之前
                invW = 200
                bpx = DWinSizeWidth/2 + (1-invSums)*invW/2
                index = 0
                
                local btnItem = GFunc_CreateButtonP("rst_rest.png", _resFunc)
                btnItem:setPosition(gdccp(bpx + invW * index, bpy))
                ResultMainMenu:addChild(btnItem)
                index = index + 1
                
                local btnItem = GFunc_CreateButtonP("fh_return.png", MainMenuCallback)
                btnItem:setPosition(gdccp(bpx + invW * index, bpy))
                ResultMainMenu:addChild(btnItem)
            else
                restlg = nil
                if GetItems(Item_Fuhuo) > 0 then
                    index = 0
                    invSums = 2
                    bpx = DWinSizeWidth/2 + (1-invSums)*invW/2
                    
                    local btnItem = GFunc_CreateButtonP("fh_use.png", onRestHp)
                    btnItem:setPosition(gdccp(bpx + invW * index, bpy))
                    ResultMainMenu:addChild(btnItem)
                    index = index + 1
                    
                    local btnItem = GFunc_CreateButtonP("fh_return.png", function()
                        _on_result = false
                        scene:removeChildByTag(10086, true)
                        _func_onShowResult(bwin, true)
                    end)
                    btnItem:setPosition(gdccp(bpx + invW * index, bpy))
                    ResultMainMenu:addChild(btnItem)
                    ---- 如果购买了时间道具,则增加"增加时间"按钮的显示
                    
                    _bgSpr = CCSprite:createWithSpriteFrameName("fh_msg.png")
                    _bgSpr:setPosition(gdccp(DWinSizeWidth/2, DWinSizeHeight/2+150))
                    layerRestul:addChild(_bgSpr,1)
                    
                    _bgSpr = CCSprite:createWithSpriteFrameName("fh_ico.png")
                    _bgSpr:setPosition(gdccp(DWinSizeWidth/2 - 50, DWinSizeHeight/2+20))
                    layerRestul:addChild(_bgSpr,1)
                    
                    lblFHSums = CCLabelTTF:create(GetItems(Item_Fuhuo), "Arial", FontSizeMax)
                    lblFHSums:setPosition(gdccp(DWinSizeWidth/2 + 50, DWinSizeHeight/2+20))
                    layerRestul:addChild(lblFHSums,1)
                else
                
                    _on_result = false
                    scene:removeChildByTag(10086, true)
                    _func_onShowResult(bwin, true)
                    return
                end
            end
        end
        
        
        _bgSpr = CCSprite:createWithSpriteFrameName(restbg)
        _bgSpr:setPosition(gdccp(DWinSizeWidth/2, DWinSizeHeight/2))
        layerRestul:addChild(_bgSpr)
        
        if restlg ~= nil then
            _bgSpr = CCSprite:createWithSpriteFrameName(restlg)
            _bgSpr:setPosition(gdccp(DWinSizeWidth/2, DWinSizeHeight/2+150))
            layerRestul:addChild(_bgSpr,1)
            
            -- 积分与击杀人数
            local spriteHL = CCSprite:createWithSpriteFrameName("rst_score.png")
            spriteHL:setPosition(gdccp(DWinSizeWidth/2 - 150, DWinSizeHeight/2+60))
            layerRestul:addChild(spriteHL,1)
            spriteHL = CCSprite:createWithSpriteFrameName("rst_skill.png")
            spriteHL:setPosition(gdccp(DWinSizeWidth/2 - 150, DWinSizeHeight/2))
            layerRestul:addChild(spriteHL,1)
            
            
            local txthl = CCLabelTTF:create(_gameScore, "Arial", FontSize4)
            txthl:setPosition(gdccp(DWinSizeWidth/2 + 50, DWinSizeHeight/2+60))
            layerRestul:addChild(txthl, 2)
            
            txthl = CCLabelTTF:create(_skill_monster_sums, "Arial", FontSize4)
            txthl:setPosition(gdccp(DWinSizeWidth/2 + 50, DWinSizeHeight/2))
            layerRestul:addChild(txthl,2 )
            
        end
        Func_DataStatis(DS_Score, _gameScore)
        
        
            
        --更新最高积分
        if newSceneUI == UI_ZJWG_Game then
            if GetMaxZJWGScore() < _gameScore then
                SetMaxZJWGScore(_gameScore)
            end
        elseif newSceneUI == UI_WXHL_Game then
            if GetMaxWXHLScore() < _gameScore then
                SetMaxWXHLScore(_gameScore)
            end
        end
        
        ---- 如果拥有"复活道具",则显示相应的按钮
    end
    
    -- 分数
    local _gui_hl = CCSprite:createWithSpriteFrameName("GUI_SC.png")
    _gui_hl:setPosition(gdccp(400, DWinSizeHeight-20))
    layer:addChild(_gui_hl, LayerIdx_Gui)
    
    local _lblScore = GameNumbers:new(vNumberScore, NumberAlginment_Left, nil, 7, true)
    _lblScore:addLayer(layer, LayerIdx_Gui)
    _lblScore:setNumber(0)
    _lblScore:setPosition(gdccp(430, DWinSizeHeight-25))
    
    -- 杀敌数
    local _gui_hl = CCSprite:createWithSpriteFrameName("GUI_Kill.png")
    _gui_hl:setPosition(gdccp(280, DWinSizeHeight-20))
    layer:addChild(_gui_hl, LayerIdx_Gui)
    
    local _lblKills = GameNumbers:new(vNumberKills, NumberAlginment_Left, nil, 2, true)
    _lblKills:addLayer(layer, LayerIdx_Gui)
    _lblKills:setNumber(0)
    _lblKills:setPosition(gdccp(300, DWinSizeHeight-25))
    
    -- 创建一个主菜单
    local _Menu = CCMenu:create()
    
    bpx = 150
    bpy = 60
    binvw = 100
    
    local layerItems = CCLayer:create()
    layer:addChild(layerItems, LayerIdx_Gui)
    
    local invW = 150
    local invSums = 3
    local bpx = DWinSizeWidth/2 + (1-invSums)*invW/2
    local bpy = 75
    local index = 0
    
    local layerItems = CCLayer:create()
    layer:addChild(layerItems, LayerIdx_Gui)
    
    _btnItem_Tips = GameItems:new(Item_Tips, _menuCallbackItem)
    _btnItem_Tips:setPosition(bpx + invW * index, bpy)
    _btnItem_Tips:addToChild(layerItems)
    index = index + 1
    
    _btnItem_AutoSl = GameItems:new(Item_AutoSl, _menuCallbackItem)
    _btnItem_AutoSl:setPosition(bpx + invW * index, bpy)
    _btnItem_AutoSl:addToChild(layerItems)
    index = index + 1
    
    _btnItemWudi = GameItems:new(Item_Wudi, _menuCallbackItem)
    _btnItemWudi:setPosition(bpx + invW * index, bpy)
    _btnItemWudi:addToChild(layerItems)
    index = index + 1
    
    --btnItem = GameItems:new(Item_HpItem, _menuCallbackItem)
    --btnItem:setPosition(DWinSizeWidth - 50, 50)
    --btnItem:addToChild(layerItems)
    ----图标
    local pv = 1
    local bgfile = "gitemBG.png"
    
    local btnItem = GFunc_CreateButtonP(bgfile, _menuCallbackItem, 1.2)
    btnItem:setPosition(gdccp(DWinSizeWidth - 50, 50))
    _Menu:addChild(btnItem, 0, Item_HpItem)
    
    --数量背景
    _txtMyhpCutBg = CCSprite:createWithSpriteFrameName("levelBg.png")
    _txtMyhpCutBg:setPosition(gdccp(DWinSizeWidth - 25, 20))
    layer:addChild(_txtMyhpCutBg, LayerIdx_Gui+1)
    --数量
    _txtMyhpCut = CCMenuItemLabel:create(CCLabelTTF:create(GetItems(Item_HpItem), "Arial", FontSizeMin))
    _txtMyhpCut:setAnchorPoint(ccp(0.5, 0.5))
    _txtMyhpCut:setPosition(gdccp(DWinSizeWidth - 25, 20))
    layer:addChild(_txtMyhpCut, LayerIdx_Gui+1)
    
    --血瓶图标
    local sp_hpicon = CCSprite:createWithSpriteFrameName(TableGameItems[Item_HpItem][PModel])
    sp_hpicon:setPosition(gdccp(DWinSizeWidth - 50, 50))
    sp_hpicon:setScale(0.7)
    layer:addChild(sp_hpicon,LayerIdx_Gui+1)
    
    updateItemsCount()
    
    
    -- 主菜单大小
    _Menu:setContentSize(CCSizeMake(DWinSizeWidth,  DWinSizeHeight))
    -- 设置坐标
    _Menu:setPosition(0, 0)
    -- 添加至主菜单层
    layer:addChild(_Menu, LayerIdx_Gui)
    
    -------------------------
    
    local _bgpx = 0
    local _bgpy = 0
    local _bg2px = 0
    local _bg2py = 799
    
    --背景
    local scfile = ""
    local scbfile = ""
    if Scene_Flat == _StageInfos[PScene] then
        scfile = "FB_py.png"
        scbfile = "FBG_py.png"
    elseif Scene_Forest == _StageInfos[PScene] then
        scfile = "FB_ss.png"
        scbfile = "FBG_ss.png"
    elseif Scene_Seaside == _StageInfos[PScene] then
        scfile = "FB_hb.png"
        scbfile = "FBG_hb.png"
    elseif Scene_Castle == _StageInfos[PScene] then
        scfile = "FB_cb.png"
        scbfile = "FBG_cb.png"
    end
    
    
    local _bgBrick = CCSprite:createWithSpriteFrameName("FB_ss.png")
    _bgBrick:setAnchorPoint(ccp(0, 0))
    _bgBrick:setPosition(gdccp(_bgpx, _bgpy))
    layer:addChild(_bgBrick, 1)
    
    local _bgBrick = CCSprite:createWithSpriteFrameName("bg2_tz.png")
    _bgBrick:setAnchorPoint(ccp(0, 0))
    _bgBrick:setPosition(gdccp(_bgpx, _bgpy))
    layer:addChild(_bgBrick, 2)
    
    -- 背景2
    _bgBrick2 = CCSprite:createWithSpriteFrameName(scbfile)
    _bgBrick2:setAnchorPoint(ccp(0, 0))
    _bgBrick2:setPosition(gdccp(_bg2px, _bg2py))
    layer:addChild(_bgBrick2, 2)
    
    --攻防生命值
    local x, y = 130, 17
    _bgBrick = CCSprite:createWithSpriteFrameName("wjian.png")
    _bgBrick:setPosition(gdccp(x, y))
    layer:addChild(_bgBrick, 2)
    
    local txtRoleAtk = CCLabelTTF:create(0, "Arial", FontSize4)
    txtRoleAtk:setAnchorPoint(ccp(0.5, 0.5))
    txtRoleAtk:setPosition(gdccp(x + 40, y))
    layer:addChild(txtRoleAtk, 2)
    
    _bgBrick = CCSprite:createWithSpriteFrameName("wdun.png")
    _bgBrick:setPosition(gdccp(x + 80, y))
    layer:addChild(_bgBrick, 2)
    
    local txtRoleDef = CCLabelTTF:create(0, "Arial", FontSize4)
    txtRoleDef:setAnchorPoint(ccp(0.5, 0.5))
    txtRoleDef:setPosition(gdccp(x + 120, y))
    layer:addChild(txtRoleDef, 2)
    --血条
    _bgpx = DWinSizeWidth/2+90
    _bgpy = 17
    local scale = 0.65
    local _HpProgressBG = CCSprite:createWithSpriteFrameName("RoleHp0.png")
    _HpProgressBG:setAnchorPoint(ccp(0.5, 0.5))
    _HpProgressBG:setPosition(gdccp(_bgpx, _bgpy))
    _HpProgressBG:setScale(scale)
    layer:addChild(_HpProgressBG, 2)
    
    local _HpProgress = CCProgressTimer:create(CCSprite:createWithSpriteFrameName("RoleHp1.png"))
    _HpProgress:setType(kCCProgressTimerTypeBar)
    _HpProgress:setAnchorPoint(ccp(0.5, 0.5))
    _HpProgress:setMidpoint(CCPointMake(0, 0))
    _HpProgress:setBarChangeRate(CCPointMake(1, 0))
    _HpProgress:setPosition(gdccp(_bgpx, _bgpy))
    _HpProgress:setPercentage(100)
    _HpProgress:setScale(scale)
    layer:addChild(_HpProgress,2)
    
    ------ 游戏进度条
    _bgpx = DWinSizeWidth/2
    _bgpy = DWinSizeHeight - 175
    local _GameProgressBG = CCSprite:createWithSpriteFrameName("prossFg.png")
    _GameProgressBG:setAnchorPoint(ccp(0.5, 0.5))
    _GameProgressBG:setPosition(gdccp(_bgpx, _bgpy))
    layer:addChild(_GameProgressBG, 2)
    
    local _GameProgress = CCProgressTimer:create(CCSprite:createWithSpriteFrameName("prossFg2.png"))
    _GameProgress:setType(kCCProgressTimerTypeBar)
    _GameProgress:setAnchorPoint(ccp(0.5, 0.5))
    _GameProgress:setMidpoint(CCPointMake(0, 0))
    _GameProgress:setBarChangeRate(CCPointMake(1, 0))
    _GameProgress:setPosition(gdccp(_bgpx, _bgpy+2))
    _GameProgress:setPercentage(0)
    layer:addChild(_GameProgress,2)
    
    
    --- 更新血条显示
    local _mylasthp = 0
    local _mylasthpmax = 0
    local function updateRoleHPUI()
        if _mylasthp ~= _Player._hp or _mylasthpmax ~= _Player._hpmax then
            _HpProgress:setPercentage((_Player._hp/ _Player._hpmax) * 100)
            
            _mylasthp = _Player._hp
            _mylasthpmax = _Player._hpmax
            
            --print(_mylasthp, _mylasthpmax)
        end
    end
    
    --- 赠送临时道具
    local _liwuTable = {
        { item = Item_HpItem, x = 1, y = 70}, 
        { item = Item_Wudi, x = 71, y = 90},
        { item = Item_Fuhuo, x = 91, y = 100},
    }
    local func_item_getnew = function()
        --随机赠送一个道具
        local idx = math.random(1,100)
        local myItem = nil
        table.foreach(_liwuTable, function(k,info)
            if idx >= info.x and idx <= info.y then
                myItem = info.item
            end
        end)
        
        if myItem ~= nil then
            local title = string.format("获得临时道具 %s x1", ShopItems_Infos[myItem][PName])
            GFunc_ShowSMessage(title)
            
            tempItemsTable[myItem] = tempItemsTable[myItem] + 1
            
            updateItemsCount()
        end
    end
    --分数
    local _gitem_lastScore = 0
    local func_item_gifts_score = function(v)
        local score = GifsItemsForScore
        while true do
            if _gitem_lastScore < score then
                if v >= score then
                    -- 获得
                    func_item_getnew()
                else
                    break
                end
            end
            score = score + GifsItemsForScore
        end
        _gitem_lastScore = v
    end
    --杀敌数
    local func_item_gifts_mon = function(v)
        if v%GifsItemsForMonster == 0 then
            func_item_getnew()
        end
    end
    
    ----------------
    -- 怪物序号
    local _monsterIndex = 0
    --- 当前场上的怪物数量
    local _monsterSums = 0
    --- 随机生成出场怪物列表
    local _monsterTable = {}
    -- 剩余怪物数量
    local _monsterLastSums = 0
    --总怪物数
    local _AllMonsterSums = 0
    if _StageInfos[PMonster] ~= nil then
        for k,mid in pairs(_StageInfos[PMonster]) do
            --数量
            local cut = 1
            if _StageInfos[PCount] ~= nil and _StageInfos[PCount][k] ~= nil then
                cut = _StageInfos[PCount][k]
            end
            for i=1,cut do
                table.insert(_monsterTable, mid)
                _monsterLastSums = _monsterLastSums + 1
            end
        end
        
        _AllMonsterSums = _monsterLastSums
    end
    
    ---随机出场
    for i=1,_monsterLastSums-1 do
        local idx = math.random(i,_monsterLastSums)
        local teMID = _monsterTable[i]
        _monsterTable[i] = _monsterTable[idx]
        _monsterTable[idx] = teMID
        --print("mid,",i,_monsterTable[i])
    end
    
    --第四关最后一个是BOSS
    if _StageInfos[PStage] == "第四大关" then
        table.insert(_monsterTable, Mon_Leader)
        _monsterLastSums = _monsterLastSums + 1
    end
    
    --无限挑战模式,怪物随机-无限
    if _StageInfos[PStage] == "无尽挑战" then
        _monsterLastSums = -1
    end
    
    local function createMonster()
        -- 没有怪物了
        if _monsterLastSums == 0 then
            return
        end
        -- 场上怪物大于最大数 
        if _monsterSums >= MonsterMax then
            return
        end
        
        ---无限怪物(无限挑战模式
        local mtype = nil
        if _monsterLastSums == -1 then
            --20%关卡为BOSS
            if _monsterIndex ~= 0 and _monsterIndex % 20 == 0 then
                mtype = Mon_Leader
            else
                --随机怪物
                local mtable={Mon_YeZhu, Mon_Eyes,Mon_Eagle,Mon_WaterE,Mon_Sworder,Mon_Soldier}
                mtype = mtable[math.random(1,#mtable)]
            end
        else
            --获得下一只怪物
            mtype = _monsterTable[1]
            table.remove(_monsterTable, 1)
            
            -- 剩余数量-1
            _monsterLastSums = _monsterLastSums - 1
        end
        local monster = _layerBattle:createRole(mtype)
        monster:setPosition(ccp(MonsterBegPosX, math.random(RoleBegPosY-gdv(5), RoleBegPosY+gdv(5))))
        _monsterSums = _monsterSums + 1
        
        
        _monsterIndex = _monsterIndex + 1
    end
    -- 移除怪物
    local function removeMonster(k)
        _monsterSums = _monsterSums - 1
        _skill_monster_sums = _skill_monster_sums + 1
        
        Func_DataStatis(DS_Skill, 1)
        
        
            
        --更新游戏进度条
        if _monsterLastSums ~= -1 then
            _GameProgress:setPercentage((_skill_monster_sums)/_AllMonsterSums * 100)
        end
        
        --杀敌数
        _lblKills:setNumber(_skill_monster_sums)
        
        --!!! 临时道具赠送
        func_item_gifts_mon(_skill_monster_sums)
    end
    
    
    
    --获取关卡相关信息,传递到消除游戏逻辑类初始化中
    --------------------- 游戏事件回调
    local function _gameComplete(iscomplete)
        _func_onShowResult(iscomplete)
    end
    local function gameAddScene(v)
        --print("gameAddScene",v)
    end
    
    local _lastCombo = 0
    local _iCombo = 0
    local function gameCombo(icombo, gemsums, bomgem)
        -- 提示解除
        clearGemsTips()
        
        --0.2秒增加一次连消
        if _lastCombo < GComboFps then
            _iCombo = _iCombo + 1
            
            Func_DataStatis(DS_Combo, _iCombo)
        else
            _iCombo = 1
        end
        
        GameingCombo = _iCombo
        _lastCombo = 0
        
        
        --显示连击数
        if bomgem~=nil then
            GFunc_ComboEffs(_iCombo, ccp(bomgem:GetPosition()))
        end
        
        
        -- 积分增加
        local adscore = 0
        local isdouble = 1
        
        if gemsums >= 12 then
            adscore = GemSumsScore[12]
        else
            adscore = GemSumsScore[gemsums]
        end
        Func_DataStatis(DS_HunJing, gemsums)
        
        ---暴走
        --if _iCombo >= 12 and _onbaozou == false then
        --    _baozoutime = 0
        --    _onbaozou = true
        --    -- 暴走模式已经开启
        --    Func_DataStatis(DS_Baozou)
        --    
        --    GFunc_ShowBaozouEffs()
        --end
        --if _onbaozou or _OnBaoForever then
        --    isdouble = 2
        --end
        
        _gameScore = _gameScore + adscore * isdouble
        _lblScore:setNumber(_gameScore)
        
        
        --!!! 临时道具赠送
        func_item_gifts_score(_gameScore)
        
        
        --_lblCombo:setString(table.concat({"连击数:",_iCombo}))
        -- 6次释放技能
        if _iCombo % ComboSkill == 0 then
            --_iCombo = 0
            --使用技能
            --print(">>>>>>>>>>>技能")
            _Player:onAttack(true)
        else
            -----------必须在范围内
            sortFunc = function(a, b)
                if a == nil or b == nil then
                    return false
                end
                local vlenght1 = ccpLength(ccp(a:getPosition()))
                local vlenght2 = ccpLength(ccp(b:getPosition()))
                return vlenght2 < vlenght1 
            end
            table.sort(mBattleObjectTable, sortFunc)
            
            local brange = false
            for k, mon in pairs(mBattleObjectTable) do
                -- 不同阵营,并且在范围内,并且可战斗
                if _Player._iTeam ~= mon._iTeam and _Player:inRange(mon) and mon._bfight then
                    brange = true
                    break
                end
            end
            
            if _Player:hasAttack() and brange then
                _Player:onAttack()
            end
        end
    end
    local function gameKills(v)
        print("gameKills",v)
    end
    local function onHurt(v)
        print("onHurt",v)
    end
    local myiFrame = 0
    local function onTimer(frame, dt, _gemTable)
        local batction = true
        if _ResBrickTime <= 0 and not _GameFirst then
            
        else
            _ResBrickTime = _ResBrickTime - dt
            batction = false
        end
        
        _layerBattle:update(dt, batction)
        
        if _GameFirst then
            return
        end
        
        -- 每隔10秒创建一个怪物
        myiFrame = myiFrame + 1
        if myiFrame % MonsterRefFps == 0 then
            createMonster()
        end
        
        --- 变幻晶魂
        if myiFrame % ChangeBrickTimer == 0 then
            local _cut = math.random(1,2)
            local i = 0
            while i < _cut do
                local row = math.random(0, Gems_Rows-1)
                local col = math.random(0, Gems_Cols-1)
                local dgem = _GGemTable[getIndex(row,col)]
                if dgem then
                    local dpx, dpy = dgem:GetPosition()
                    _func_deleteGemJump(dgem, nil, true)
                    -- 删除原来的,变成生成新的
                    local cgem = createGems(row, col)
                    cgem.img:setPosition(dpx,dpy)
                    _func_Set_GemPos(cgem, row, col)
                end
                i = i + 1
            end
        end
        
        ------------------------------怪物动画
        
        
        _lastCombo = _lastCombo + dt
        
        --更新玩家生命条
        updateRoleHPUI()
        
        --- 玩家死亡则结束游戏
        local haslife = false
        --当前玩家死亡则切换其它玩家,如果没有其它玩家了,则结束游戏 
        if _Player._hp <= 0 then
            --死亡后头像变灰
            _PlayerHTable[_Player.id]:setColor(ccc3(100,100,100))
            
            for k, py in pairs(_PlayerTable) do
                print(k,py._hp)
                if py._hp > 0 then
                    _func_changePlayer(k)
                    haslife = true
                    break
                end
            end
            
            if not haslife then
                _gameComplete(false)
                return
            end
        end
        
        -- 如果怪物没有了则游戏结束
        if _monsterLastSums == 0 and _monsterSums <= 0 then
            _gameComplete(true)
            return
        end
        
        table.foreach(mBattleObjectTable, function(k, monster)
            if monster ~= nil and monster._iTeam ~= 1 then
                if monster._hp <= 0 then
                    --死亡
                    monster._status = Status_Death
                    --移除
                    _layerBattle:deleteRole(monster)
                    removeMonster(monster.key)
                end
            end
        end)
        
        -------------暴走计时
        if _onbaozou then
            _baozoutime = _baozoutime + dt
            --- 暴走计时
            if _baozoutime > GBaoZouTimer then
                _onbaozou = false
                if not _OnBaoForever then
                    Gfunc_DelBazouEffs()
                end
            end
        end
        
        if _OnBaoForever then
            if os.clock() - _OnBaozouTime >= 180 then
                _func_baozou(false)
            end
        end
        
        ------------- 无敌计时
        if _OnWudi then
            _OnWudiLTime = _OnWudiLTime - dt
            if _OnWudiLTime <= 0 then
                _func_wudi(false)
            end
        end
        
        ------提示效果
        _lastTips = _lastTips + dt
        if not _onShowTips and _lastTips >= _TipsTimes then
            BtnTipsCallback()
        end
    end
    
    
    --- 新回合的回调
    local function onNewRound()
        -- 延迟判定当前宝石阵是否可排列（防卡
        _timerIDNew = CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(onNewRoundLeat,0.1, false)
        --onNewRoundLeat()
    end
    
    local gamefunc = {
        [PFunc_Complete] = _gameComplete,
        [PFunc_AddScore] = gameAddScene,
        [PFunc_Combo] = gameCombo,
        [PFunc_Kills] = gameKills,
        [PFunc_Hurts] = onHurt,
        [PFunc_Timer] = onTimer,
        [PFunc_newRound] = onNewRound,
    }
    
    -- 三消游戏UI
    
    -- 宝石填充模式
    layer:addChild(Create_Game_Scene(GameMode_Clicked, gemType, PlayMode_TiaoZhan, gamefunc), 3)
    
    --- 切换角色
    local nodeHeads = CCNode:create()
    --头像显示顺序
    _func_changePlayer = function (rid, blr)
        table.foreach(_PlayerTable, function(k,py)
            if rid == k then
                _Player = py
                _Player:Show()
                
                _Player.isWudi = _OnWudi
                _Player.isBaozou = _OnBaoForever
                
                --更新玩家攻防数值
                txtRoleAtk:setString(_Player._atk)
                txtRoleDef:setString(_Player._def)
            else
                py:Hide()
                --print("_______deadth", py._hp)
                _Player.isWudi = false
                _Player.isBaozou = false
            end
            
            if py._hp <= 0 then
                _PlayerHTable[py.id]:setColor(ccc3(100,100,100))
            else
                _PlayerHTable[py.id]:setColor(ccc3(255,255,255))
            end
        end)
        
        --头像切换效果
        table.foreach(_PlayerHTable, function(k,v)
            local mid = rid - k
            if mid <= -2 then
                mid = 1
            elseif mid >= 2 then
                mid = -1
            end
            --缩放
            local rlevel = 5-k
            if blr then
                if mid == 1 then
                    rlevel = 4
                elseif mid == -1 then
                    rlevel = 3
                end
            else
                if mid == 1 then
                    rlevel = 3
                elseif mid == -1 then
                    rlevel = 4
                end
            end
            
            local at = 0.5
            if mid == 0 then
                v:runAction(CCScaleTo:create(at, 1))
                rlevel = 5
            else
                v:runAction(CCScaleTo:create(at, 0.7))
            end
            
            --print(mid, rlevel)
            nodeHeads:removeChild(v, false)
            nodeHeads:addChild(v, rlevel)
            
            --移动
            v:runAction(CCMoveTo:create(at, gdccp(50 + mid*40,50)))
        end)
    end
    
    local rolesums = 1
    local showIndexHead = 0
    --- 加载玩家角色
    if _StageInfos[PRole] == Role_All then
        -- 加载三个角色
        _PlayerTable[Role_Soldier] = _layerBattle:createRole(Role_Soldier, ccp(PlayerBegPosX, RoleBegPosY))
        _PlayerTable[Role_Master] = _layerBattle:createRole(Role_Master, ccp(PlayerBegPosX, RoleBegPosY))
        _PlayerTable[Role_Archer] = _layerBattle:createRole(Role_Archer, ccp(PlayerBegPosX, RoleBegPosY))
        
        _PlayerHTable[Role_Soldier] = CCSprite:createWithSpriteFrameName("head_z.png")
        _PlayerHTable[Role_Master] = CCSprite:createWithSpriteFrameName("head_m.png")
        _PlayerHTable[Role_Archer] = CCSprite:createWithSpriteFrameName("head_g.png")
        
        rolesums = 3
        _func_changePlayer(Role_Soldier)
    else
        _PlayerTable[_StageInfos[PRole]] = _layerBattle:createRole(_StageInfos[PRole], ccp(PlayerBegPosX, RoleBegPosY))
        
        local file = nil
        if _StageInfos[PRole] == Role_Soldier then
            file = "head_z.png"
        elseif _StageInfos[PRole] == Role_Archer then
            file = "head_g.png"
        elseif _StageInfos[PRole] == Role_Master then
            file = "head_m.png"
        end
        if file ~= nil then
            _PlayerHTable[_StageInfos[PRole]] = CCSprite:createWithSpriteFrameName(file)
        end
        
        _func_changePlayer(_StageInfos[PRole])
        showIndexHead = _StageInfos[PRole]-1
    end
    
    layer:addChild(nodeHeads,2)
    table.foreach(_PlayerTable, function(k,py)
        py._iTeam = 1
        --_PlayerHTable[k]:setPosition(gdccp(50,50))
        --nodeHeads:addChild(_PlayerHTable[k])
    end)
    
    --local monster = _layerBattle:createRole(Mon_Leader)
    --monster:setPosition(gdccp(MonsterBegPosX, RoleBegPosY))
    --_monsterSums = _monsterSums + 1
    createMonster()--怪物一只
    
    
    ---程序结束时释放内存
    --_layerBattle.Remove()
    getSwapList()
    
    
    layer:addChild(_layerBattle.layer, 3)
    
    -----------------------------------------------
    local _mousex, _mousey = 0 ,0
    local _beginpx = 0
    local function onTouchBegin(x, y)
        _mousex, _mousey = x, y
        _beginpx = x
        
        return 1
    end
    
    local function onTouchMoved(x, y)
    end
    
    local function changeTOPY(bnext)
        Play_Effect(sme_Click)
        
        --是否还有活着的玩家
        local haslife = false
        for k, py in pairs(_PlayerTable) do
            if py._hp > 0 then
                haslife = true
                break
            end
        end
        
        if haslife then
            if bnext then
                showIndexHead = showIndexHead+1
            else
                showIndexHead = showIndexHead-1
            end
            
            if showIndexHead >= rolesums then
                showIndexHead = 0
            elseif showIndexHead < 0 then
                showIndexHead = rolesums-1
            end
            
            --必须是活着的
            if _PlayerTable[showIndexHead+1]._hp > 0 then
                _func_changePlayer(showIndexHead+1, bnext)
            else
                changeTOPY(bnext)
            end
        end
    end
    
    local function onTouchEnded(x, y)
        -- 切换显示的列表
        if x > _beginpx + 20 then
            changeTOPY(true)
        elseif x < _beginpx - 20 then
            changeTOPY(false)
        end
    end

    -- 触摸操作
    local function onTouch(eventType, x, y)
        if eventType == CCTOUCHBEGAN then
            return onTouchBegin(x, y)
        elseif eventType == CCTOUCHMOVED then
            return onTouchMoved(x, y)
        elseif eventType == CCTOUCHENDED then
            return onTouchEnded(x, y)
        end
    end
    
    --layer:setTouchEnabled(true)
    --layer:registerScriptTouchHandler(onTouch)
    
    
    ------------切换角色按钮
    local menu = CCMenu:create()
    local btnItem = CCMenuItemLabel:create(CCLabelTTF:create("", "Arial", FontSizeMax))
    btnItem:registerScriptTapHandler(changeTOPY)
    btnItem:setContentSize(CCSizeMake(100,100))
    menu:addChild(btnItem)
    menu:setPosition(gdccp(50,50))
    layer:addChild(menu,10)
    
    
    Func_ShowGameTutorial(UI_ZJWG_Game, function()
        Func_BeginResFills()
        if newSceneUI == UI_ZJWG_Game then
            --- 游戏目标显示
            local _AllMonsterSums = 0
            local _monsterLastSums = 0
            if Stage_Infos_ZJWG[stage][PMonster] ~= nil then
                for k,mid in pairs(Stage_Infos_ZJWG[stage][PMonster]) do
                    --数量
                    local cut = 1
                    if Stage_Infos_ZJWG[stage][PCount] ~= nil and Stage_Infos_ZJWG[stage][PCount][k] ~= nil then
                        cut = Stage_Infos_ZJWG[stage][PCount][k]
                    end
                    for i=1,cut do
                        _monsterLastSums = _monsterLastSums + 1
                    end
                end
                
                _AllMonsterSums = _monsterLastSums
            end
            GFunc_CreateShowMessage("通关条件", string.format("击杀 %d 名敌人。", _AllMonsterSums), false, scene)
        end
    end, scene)

    return layer
end

function Create_TJMS_SceneRun(stage)
    scene = CCScene:create()
    layer = CCLayer:create()
    scene:addChild(layer)
    
    newSceneUI = UI_ZJWG_Game

    initWithLayer(stage)
    
    scene:addChild(CreateGameStopLayer(ccp(50, DWinSizeHeight-50)))
    --GameReplaceScne(scene, UI_ZJWG_Game)
    
    
    GameSetScne(scene, UI_ZJWG_Game)
    
    return scene, UI_ZJWG_Game
end


function Create_WXHL_SceneRun()
    scene = CCScene:create()
    layer = CCLayer:create()
    scene:addChild(layer)
    
    newSceneUI = UI_WXHL_Game

    initWithLayer(#Stage_Infos_ZJWG)
    
    scene:addChild(CreateGameStopLayer(ccp(50, DWinSizeHeight-50)))
    
    --GameReplaceScne(scene, UI_WXHL_Game)
    GameSetScne(scene, UI_WXHL_Game)
    
    --玩无限回廊成就
    Func_DataStatis(DS_ModePlay, GameMode_WXHL)

    return scene, UI_WXHL_Game
end

function Create_TJMS_Scene(stage)
    LoadingTutorial(UI_ZJWG_Game, Create_TJMS_SceneRun, stage)
end
function Create_WXHL_Scene(stage)
    LoadingTutorial(UI_WXHL_Game, Create_WXHL_SceneRun, stage)
end







----------------- 显示关卡目标

GFunc_CreateShowAchieve11111111 = function(ach)
    local function unLockBtn()
        AchFormSums = AchFormSums - 1
        CCDirector:sharedDirector():getRunningScene():removeChild(layer, true)
    end
    
    --背景
    local px = DWinSizeWidth/2
    local py = DWinSizeHeight/2 + 120
    local _bgBrick = CCSprite:createWithSpriteFrameName(s_Space_sbg)
    _bgBrick:setAnchorPoint(ccp(0.5, 0.5))
    _bgBrick:setPosition(gdccp(px, py))
    layer:addChild(_bgBrick)
    
            
    --"成就解锁"
    local txt = CCLabelTTF:create("关卡目标", "Arial", FontSize10)
    txt:setColor(ccc3(110, 255, 110))
    txt:setPosition(gdccp(px + 60, py + 100))
    layer:addChild(txt)
    
    --成就名称
    local txtn = CCLabelTTF:create(achInfo[PName], "Arial", FontSize10)
    txtn:setColor(ccc3(246, 196, 124))
    txtn:setPosition(gdccp(px + 90, py))
    layer:addChild(txtn)
    
    --提示点击按钮
    local txtT = CCLabelTTF:create("请在成就栏查看", "Arial", FontSize)
    txtT:setColor(ccc3(124,150,246))
    txtT:setPosition(gdccp(px + 150, py - 110))
    local arr1 = CCArray:create()
    arr1:addObject(CCFadeTo:create(0.5, 100))
    arr1:addObject(CCFadeTo:create(0.5, 255))
    txtT:runAction(CCRepeatForever:create(CCSequence:create(arr1)))
    layer:addChild(txtT)
    
    --显示动画
    for k, obj in pairs({txt, txtn, txtT}) do
        local array = CCArray:create()
        array:addObject(CCFadeIn:create(1))
        array:addObject(CCFadeTo:create(1.5, 200))
        array:addObject(CCFadeTo:create(0.5, 0))
        local seq    = CCSequence:create(array)
        obj:runAction(seq)
    end
    
    local array = CCArray:create()
    array:addObject(CCFadeIn:create(1))
    array:addObject(CCFadeTo:create(1.5, 200))
    array:addObject(CCFadeTo:create(0.5, 0))
    local seq    = CCSequence:create(array)
    _bgBrick:runAction(CCSequence:createWithTwoActions(seq, CCCallFuncN:create(unLockBtn)))
    
    
    CCDirector:sharedDirector():getRunningScene():addChild(layer)
end

